<?php
namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\service\DouAccessToken;
use think\Db;
use think\Exception;
use think\Request;
use think\Log;

class Push extends BaseController
{

    // 消息推送
    public function index()
    {
//        Log::write('测试日志信息');

        // 订单创建消息
        $data = Request::instance()->post();

        Log::write($data);

        // 获取access_token
        $dou = new DouAccessToken();
        $result = $dou->get();
        // 参数
        $app_key = config('dou.app_id');
        $app_secret = config('dou.app_secret');
        $access_token = $result["data"]["access_token"];
        $order_data = json_decode($data[0]["data"],true);
        $order_id = $order_data['p_id']."A";
        $param_json = '{"order_id":"'.$order_id.'"}';
        $timestamp = date('Y-m-dH:i:s');
        $sign = $app_secret."app_key".$app_key.
            "methodorder.detailparam_json".$param_json.
            "timestamp".$timestamp."v2".$app_secret;
        $sign = md5($sign);

        // 获取订单详情url
        $order_detail_url = sprintf(config('dou.order_detail'), $app_key, $access_token, $param_json, $timestamp, $sign);

        // 获取订单详情
        $order_result = curl_get($order_detail_url);
        $order_result = json_decode($order_result, true);

        if($order_result['data']['list']){
            Db::startTrans();
            try {
                $origin = $order_result['data']['list'][0]['child'][0];

                // 数据库是否存在这条订单
                $is_order = Db::name('order')->where('ordernum',$origin['order_id'])->field('id,money,dealer_id')->find();

                if($is_order){
                    $order_status = $origin['order_status'];
                    $update_data = [];
                    $update_data['status'] = $order_status;

                    if ($order_status == 5)
                    {
                        $ratio = Db::name('commission')->where('dealer_id',$is_order['dealer_id'])->order('updatetime desc')->field('firstratio')->find();

                        if($ratio){
                            $commission = bcmul($is_order['money'],$ratio['firstratio'],2);
                            $commission = bcdiv($commission,100,2);
                            $update_data['commission'] = $commission;
                            $update_data['commission_status'] = '1';
                            $update_data['commission_available'] = $commission;
                        }
                    }

                    Db::name('order')->where('ordernum',$origin['order_id'])->update($update_data);
                }else{
                    // 下单用户判定 数据库是否存在对应用户
                    $phone = $origin['post_tel'];
                    $consumer = Db::name('consumer')->where('phone',$phone)->field('id,admin_id,consumer_id,dealer_id')->find();

                    // 准备订单数据
                    if ($consumer){
                        $add_data = [];
                        $add_data['ordernum'] = $origin['order_id'];
                        $add_data['goods'] = $origin['product_name'];
                        $add_data['goodsimage'] = $origin['product_pic'];
                        $add_data['ordertime'] = date('Y-m-d H:i:s', $origin['create_time']);
                        $add_data['status'] = $origin['order_status'];
                        $add_data['money'] = bcdiv($origin['total_amount'],100,2);
                        $add_data['shop_id'] = $origin['shop_id'];
                        $add_data['admin_id'] = $consumer['admin_id'];
                        $add_data['dealer_id'] = $consumer['dealer_id'];
                        $add_data['head_id'] = $consumer['consumer_id'];
                        $add_data['consumer_id'] = $consumer['id'];
                        $add_data['createtime'] = $origin['create_time'];
                        $add_data['receiver'] = $origin['post_receiver'];
                        $add_data['phone'] = $phone;
                        $address = $origin['post_addr'];
                        $add_data['address'] = $address['province']['name'].$address['city']['name'].$address['town']['name'].$address['detail'];

                        Db::name('order')->insert($add_data);
                    }
                }

                Db::commit();

                return [
                    'code'    => 0,
                    'message' => 'success'
                ];

            }
            catch (Exception $ex)
            {
                Db::rollback();
                Log::error($ex);

                return false;
            }
        }else{
            return [
                'code'    => 0,
                'message' => 'success'
            ];
        }
    }
}